package com.travelsky.airchina.boarding.web.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.travelsky.airchina.boarding.domain.NewsColumn;
import com.travelsky.airchina.boarding.domain.Resource;
import com.travelsky.airchina.boarding.domain.Role;
import com.travelsky.airchina.boarding.domain.RoleColumn;
import com.travelsky.airchina.boarding.dto.TreeNode;
import com.travelsky.airchina.boarding.service.NewsColumnService;
import com.travelsky.airchina.boarding.service.ResourceService;
import com.travelsky.airchina.boarding.service.RoleService;
import com.travelsky.airchina.boarding.util.TreeNodeUtil;
@Controller
@RequestMapping(value="/system/role")
public class RoleController {
	@Autowired
	private RoleService roleService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private NewsColumnService newsColumnService;
	/**
	 * 转到创建角色页面
	 * @param model
	 * @return
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String toCreate(Model model) {
		Role role = new Role();
		role.setSortOrder(roleService.getRoleSum());
		model.addAttribute(role);
		getResourceTree(model,null,"checkboxId");
		getNewsColumnTree(model,null,"columnIdCheckboxId");
		return "system/role/createForm";
	}
	/**
	 * 获得资源树
	 * @param model
	 * @param checkedIdList
	 * @param checkboxName 复选框的name值
	 */
	private void getResourceTree(Model model,List<Long> checkedIdList,String checkboxName){
		List<Resource> list = resourceService.findAllResource("url","1");
		if(list!=null && list.size()>0){
			List<TreeNode>  treeNodeList =  new ArrayList<TreeNode>();
			TreeNode rootNode = new TreeNode();
			rootNode.setId("0");
			rootNode.setName("操作权限");
			rootNode.setPid("-1");
			rootNode.setCheckboxName(checkboxName);
			treeNodeList.add(rootNode);
			if(checkedIdList!=null && checkedIdList.size()>0){
				rootNode.setChecked(true);
				for(Resource temp:list){
					TreeNode treeNode = new TreeNode();
					treeNode.setId(temp.getId()!=null?temp.getId().toString():"");
					treeNode.setPid(temp.getParentResource()!=null?temp.getParentResource().getId().toString():"0");
					treeNode.setName(temp.getName());
					treeNode.setTitle(temp.getName());
					treeNode.setCheckboxName(checkboxName);
					if(checkedIdList.contains(temp.getId())){
						treeNode.setChecked(true);
					}
					treeNodeList.add(treeNode);
				}
				checkedIdList = null;
			}else{
				for(Resource temp:list){
					TreeNode treeNode = new TreeNode();
					treeNode.setId(temp.getId()!=null?temp.getId().toString():"");
					treeNode.setPid(temp.getParentResource()!=null?temp.getParentResource().getId().toString():"0");
					treeNode.setName(temp.getName());
					treeNode.setTitle(temp.getName());
					treeNode.setCheckboxName(checkboxName);
					treeNodeList.add(treeNode);
				}
			}
			model.addAttribute("treeContent", TreeNodeUtil.createJsArray(treeNodeList,"root"));
		}
	}
	/**
	 * 获得栏目树
	 * @param model
	 * @param checkedIdList 
	 * @param checkboxName 复选框的name值
	 */
	private void getNewsColumnTree(Model model,List<Long> checkedIdList,String checkboxName){
		List<NewsColumn> list = newsColumnService.findAllNewsColumns();
		if(list!=null && list.size()>0){
			List<TreeNode>  treeNodeList =  new ArrayList<TreeNode>();
			TreeNode rootNode = new TreeNode();
			rootNode.setId("0");
			rootNode.setName("新闻栏目");
			rootNode.setPid("-1");
			rootNode.setCheckboxName(checkboxName);
			treeNodeList.add(rootNode);
			if(checkedIdList!=null && checkedIdList.size()>0){
				rootNode.setChecked(true);
				for(NewsColumn temp:list){
					TreeNode treeNode = new TreeNode();
					treeNode.setId(temp.getId()!=null?temp.getId().toString():"");
					treeNode.setPid(temp.getParentColumn()!=null?temp.getParentColumn().getId().toString():"0");
					treeNode.setName(temp.getName());
					treeNode.setTitle(temp.getName());
					treeNode.setCheckboxName(checkboxName);
					if(checkedIdList.contains(temp.getId())){
						treeNode.setChecked(true);
					}
					treeNodeList.add(treeNode);
				}
				checkedIdList = null;
			}else{
				for(NewsColumn temp:list){
					TreeNode treeNode = new TreeNode();
					treeNode.setId(temp.getId()!=null?temp.getId().toString():"");
					treeNode.setPid(temp.getParentColumn()!=null?temp.getParentColumn().getId().toString():"0");
					treeNode.setName(temp.getName());
					treeNode.setTitle(temp.getName());
					treeNodeList.add(treeNode);
					treeNode.setCheckboxName(checkboxName);
				}
			}
			model.addAttribute("newsColumnTreeContent", TreeNodeUtil.createJsArray(treeNodeList,"newsColumnTreeRoot"));
		}
	}
	/**
	 * 创建角色
	 * @param user
	 * @param result
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public String create(@ModelAttribute("role") Role role, BindingResult result,Model model,HttpServletRequest request) {
		role.setStatus("1");
		//checkboxId 是在toCreate()方法中设置的
		String[] resourceIds = request.getParameterValues("checkboxId");
		if(resourceIds!=null && resourceIds.length>0){
			List<Resource> list = new ArrayList<Resource>();
			for(String resourceId:resourceIds){
				if(!"0".equals(resourceId)){
					Resource resource = new Resource();
					resource.setId(new Long(resourceId));
					list.add(resource);
				}
			}
			role.setResources(list);
		}
		//columnIdCheckboxId 是在toCreate()方法中设置的
		String[] columnIds = request.getParameterValues("columnIdCheckboxId");
		if(columnIds!=null && columnIds.length>0){
			List<RoleColumn> list = new ArrayList<RoleColumn>();
			for(String columnId:columnIds){
				if(!"0".equals(columnId)){
					RoleColumn newsColumn = new RoleColumn();
					newsColumn.setColumnId(new Long(columnId));
					list.add(newsColumn);
				}
			}
			role.setRoleColumns(list);
		}
		roleService.saveOrUpdateRole(role);
		setSessionOperationFlag(request,"t");
		return "redirect:/system/role/"+role.getId();
	}
	/**
	 * 角色列表首页
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/manage", method=RequestMethod.GET)
	public String manage(Model model) {
		List<Role> list = roleService.findAllRoles();
		model.addAttribute("list",list);
		return "system/role/roleList";
	}
	/**
	 * 转到修改角色页面
	 * @param id 角色的主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
	public String toUpdate(@PathVariable Long id, Model model) {
		Role role = roleService.getRoleWithColumn(id);
		model.addAttribute(role);
		List<Long> checkedIdList = null;
		if(role.getResources()!=null && role.getResources().size()>0){
			checkedIdList = new ArrayList<Long>();
			for(Resource temp:role.getResources()){
				checkedIdList.add(temp.getId());
			}
		}
		List<Long> newsColumnCheckedIdList = null;
		if(role.getRoleColumns()!=null && role.getRoleColumns().size()>0){
			newsColumnCheckedIdList = new ArrayList<Long>();
			for(RoleColumn temp:role.getRoleColumns()){
				newsColumnCheckedIdList.add(temp.getColumnId());
			}
		}
		getResourceTree(model,checkedIdList,"checkboxId");
		getNewsColumnTree(model,newsColumnCheckedIdList,"columnIdCheckboxId");
		return "system/role/updateForm";
	}
	/**
	 * 转到修改角色页面
	 * @param id 角色的主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(@ModelAttribute("role") Role role, BindingResult result,Model model,HttpServletRequest request) {
		//checkboxId 是在toUpdate()方法中设置的
		String[] resourceIds = request.getParameterValues("checkboxId");
		if(resourceIds!=null && resourceIds.length>0){
			List<Resource> list = new ArrayList<Resource>();
			for(String resourceId:resourceIds){
				if(!"0".equals(resourceId)){
					Resource resource = new Resource();
					resource.setId(new Long(resourceId));
					list.add(resource);
				}
			}
			role.setResources(list);
		}
		//columnIdCheckboxId 是在toUpdate()方法中设置的
		String[] columnIds = request.getParameterValues("columnIdCheckboxId");
		if(columnIds!=null && columnIds.length>0){
			List<RoleColumn> list = new ArrayList<RoleColumn>();
			for(String columnId:columnIds){
				if(!"0".equals(columnId)){
					RoleColumn newsColumn = new RoleColumn();
					newsColumn.setColumnId(new Long(columnId));
					list.add(newsColumn);
				}
			}
			role.setRoleColumns(list);
		}
		roleService.saveOrUpdateRole(role);
		setSessionOperationFlag(request,"t");
		return "redirect:/system/role/"+role.getId();
	}
	/**
	 * 查看角色信息
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="{id}", method=RequestMethod.GET)
	public String getView(@PathVariable Long id, Model model,HttpServletRequest request) {
		Role role = roleService.getRoleWithColumn(id);
		model.addAttribute(role);
		List<Long> checkedIdList = null;
		if(role.getResources()!=null && role.getResources().size()>0){
			checkedIdList = new ArrayList<Long>();
			for(Resource temp:role.getResources()){
				checkedIdList.add(temp.getId());
			}
		}
		List<Long> newsColumnCheckedIdList = null;
		if(role.getRoleColumns()!=null && role.getRoleColumns().size()>0){
			newsColumnCheckedIdList = new ArrayList<Long>();
			for(RoleColumn temp:role.getRoleColumns()){
				newsColumnCheckedIdList.add(temp.getColumnId());
			}
		}
		getResourceTree(model,checkedIdList,"checkboxId");
		getNewsColumnTree(model,newsColumnCheckedIdList,"columnIdCheckboxId");
		setRequestOperationFlag(request);
		return "system/role/view";
	}
	/**
	 * 操作后设置操作成功或失败的标志
	 * @param request
	 * @param operationFlag
	 */
	private void setSessionOperationFlag(HttpServletRequest request,String operationFlag){
		request.getSession().setAttribute("operationFlag", operationFlag);
	}
	/**
	 * 从session中取得操作成功或失败的标志,并设置在request
	 * @param request
	 */
	private void setRequestOperationFlag(HttpServletRequest request){
		HttpSession session = request.getSession();
		String operationFlag = (String)session.getAttribute("operationFlag");
		if(operationFlag!=null){
			request.setAttribute("operationFlag", operationFlag);
			session.removeAttribute("operationFlag");
		}
	}
}